<template>
    <div style="width: 100%;">
        <TitleTips title="预算内容" />
        <CardBox v-for="(item, index) in list" :key="index" :title="item.itemName">
            <el-form ref="form" :model="item" class="size-auto width-100" :rules="rules" :inline="true" size="medium" label-width="100px">
                <el-row :gutter="24">
                    <el-col :lg="8" :xl="6">
                        <el-form-item label="工程量" prop="workAmount">
                            <el-input v-model.trim="item.workAmount" maxlength="15" clearable placeholder="支持小数点后6位" @change="handleComputed(item)" />
                        </el-form-item>
                    </el-col>
                    <el-col :lg="8" :xl="6">
                        <el-form-item label="单位" prop="arithmeticalUnit">
                            <el-input v-model.trim="item.arithmeticalUnit" maxlength="50" show-word-limit clearable placeholder="请输入" />
                        </el-form-item>
                    </el-col>
                    <el-col :lg="8" :xl="6">
                        <el-form-item label="基本费用" prop="basicFee">
                            <el-input v-model.trim="item.basicFee" maxlength="50" show-word-limit clearable placeholder="请输入" @change="handleComputed(item)" />
                        </el-form-item>
                    </el-col>
                    <el-col :lg="8" :xl="6">
                        <el-form-item label="调整系数" prop="adjustmentFactor">
                            <el-input v-model.trim="item.adjustmentFactor" maxlength="15" clearable placeholder="支持小数点后6位" @change="handleComputed(item)" />
                        </el-form-item>
                    </el-col>
                    <el-col :lg="8" :xl="6">
                        <el-form-item label="预算金额" prop="budgetMoney">
                            <el-input v-model.trim="item.budgetMoney" disabled maxlength="15" clearable placeholder="支持小数点后6位" @change="handleComputed(index)">
                                <i slot="suffix" class="el-input__icon input-unit">元</i>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="编制说明" class="margin-r-0 block-item">
                            <el-input v-model.trim="item.description" type="textarea" maxlength="200" show-word-limit clearable placeholder="请输入" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </CardBox>
    </div>
</template>

<script>
import BigNumber from 'bignumber.js'
import { isNumber6 } from '@/utils/validate'
import { MaintenanceProjectConfigModel } from '@/models' 

export default {
    name: 'FormCard',
    props: {
        form: {
            type: Array,
            default: () => ([])
        },
        type: {
            type: String,
            default: 'add'
        }
    },
    data() {
        return {
            list: [],
            rules: {
                workAmount: [{ validator: this.validNum, trigger: 'blur' }],
                basicFee: [{ validator: this.validNum, trigger: 'blur' }],
                adjustmentFactor: [{ validator: this.validNum, trigger: 'blur' }]
            },
            model: new MaintenanceProjectConfigModel(),
            projectList: [] 
        }
    },
    watch: {
        form: {
            handler(newVal) {
                if (newVal.length > 0) {
                    this.list = newVal
                    // 让父组件的加载动画关闭
                    this.$emit('update:loading', false)
                }
            },
            // immediate: true,
            deep: true
        }
    },
    created() {
        if (this.type === 'add' || this.type === 'change') {
            this.init()
        }
    },
    methods: {
        init() {
            const template = {
                workAmount: null,
                arithmeticalUnit: null,
                basicFee: null,
                adjustmentFactor: null,
                budgetMoney: null,
                description: null
            }
            this.getList().then(() => {
                this.list = this.projectList.map(item => {
                    const project = item[item.length - 1]
                    // 所有父级到目标的id集合
                    const levelIds = item.map(m => m.id)
                    const levelNames = item.map(m => m.name)
                    return {
                        levelId: levelIds.toString(),
                        levelName: levelNames.toString(),
                        itemId: project.id,
                        itemName: project.name,
                        content: project.content,
                        ...template
                    }
                })
                // 让父组件的加载动画关闭
                this.$emit('update:loading', false)
            })
        },
        getList() {
            return this.model.getList({ pageNo: 1, pageSize: 1000 }).then(res => {
                this.getProject(res.list)
            })
        },
        getProject(arr, parentIds = []) {
            arr.forEach(item => {
                if (item.children && item.children.length > 0) {
                    parentIds.push({ id: item.id, name: item.name, content: item.content })
                    this.getProject(item.children, parentIds)
                } else {
                    // 0为养护类型，不需要；1为养护项目，需要
                    if (item.type === 0) { return }
                    if (item.type === 1) {
                        parentIds.push({ id: item.id, name: item.name, content: item.content })
                        this.projectList.push(JSON.parse(JSON.stringify(parentIds)))
                    }
                }
                // 每次执行完毕，把父id最后一个删掉
                parentIds.splice(parentIds.length - 1, 1)
            })
        },
        // 针对新建年度养护预算做的计算金额
        handleComputed(item) {
            const a = item['workAmount']
            const b = item['basicFee']
            const c = item['adjustmentFactor']
            // 如果3个值任意一个没有则不处理
            if (!a || !b || !c) { return }
            const value = Number(new BigNumber(a).times(b).times(c).toFixed(6))
            this.$set(item, 'budgetMoney', value || null)
        },
        handleValidate() {
            const list = []
            const validas = []
            this.$refs['form'].forEach((item, index) => {
                list.push(new Promise(resolve => {
                    item.validate(valida => {
                        validas.push(valida)
                        resolve()
                    })
                })
                )
            })
            return Promise.all([...list]).then(() => {
                const res = !validas.some(item => item === false)
                return res
            }).catch(() => {
                return false
            })
        },
        validNum(rule, value, callback) {
            if (value && !isNumber6(value)) {
                callback(new Error('填写格式错误'))
            } else {
                callback()
            }
        }
    },
}
</script>

<style lang="scss" scoped>
.el-form--inline.size-auto.width-100 {
    ::v-deep {
        // form的label-width：72px 根据实际label宽度修改
        .el-form-item__content {
            width: calc(100% - 100px);
        }
    }    
}
.margin-b-0 {
    margin-bottom: 0;
}
.add-box {
    width: 100%;
    height: 40px;
    line-height: 40px;
    margin-bottom: 24px;
    background: rgb(250, 250, 250);
    border: 1px solid #F5F7FA;
    border-radius: 5px;
    text-align: center;
    cursor: pointer;
    &:hover {
        background: rgb(240, 240, 240);
    }
    i {
        color: #171725;
        font-style: normal;
    }
}
</style>
